<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="员工姓名" prop="userId">
        <UserSelect @node-change="handleNodeChange" v-model="formData.userId" />
      </el-form-item>
      <!-- <el-form-item label="员工id" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入员工id" />
      </el-form-item>
      <el-form-item label="员工姓名" prop="realName">
        <el-input v-model="formData.realName" placeholder="请输入员工姓名" />
      </el-form-item> -->
      <!-- <el-form-item label="调出部门" prop="originalDeptId" disabled>
        <el-input v-model="formData.originalDeptId" placeholder="请输入调出部门" />
      </el-form-item> -->
      <el-form-item label="调出部门" prop="originalDeptName" >
        <el-input v-model="formData.originalDeptName" placeholder="请输入调出部门" disabled />
      </el-form-item>
      <el-form-item label="调入部门" prop="newDeptId">
        <el-tree-select
          v-model="formData.newDeptId"
          :data="deptList"
          :props="defaultProps"
          check-strictly
          node-key="id"
          placeholder="请选择调入部门"
          @node-click="handleNewDeptClick"
        />
      </el-form-item>
      
      <el-form-item label="调动日期" prop="transferDate">
        <el-date-picker
          v-model="formData.transferDate"
          type="date"
          value-format="x"
          placeholder="选择调动日期"
        />
      </el-form-item>
      <el-form-item label="调动原因" prop="transferReason">
        <el-input v-model="formData.transferReason" placeholder="请输入调动原因" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { PersonnelTransferApi, PersonnelTransferVO } from '@/api/oa/personneltransfer'
import UserSelect  from '@/views/system/user/UserSelect.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'

/** 人事调动记录 表单 */
defineOptions({ name: 'PersonnelTransferForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  userId: undefined,
  realName: undefined,
  originalDeptId: undefined,
  originalDeptName: undefined,
  newDeptId: undefined,
  newDeptName: undefined,
  transferReason: undefined,
  transferDate: undefined,
})
const formRules = reactive({
  userId: [{ required: true, message: '员工id不能为空', trigger: 'blur' }],
  realName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  originalDeptId: [{ required: true, message: '调出部门不能为空', trigger: 'blur' }],
  originalDeptName: [{ required: true, message: '调出部门不能为空', trigger: 'blur' }],
  newDeptId: [{ required: true, message: '调入部门不能为空', trigger: 'blur' }],
  newDeptName: [{ required: true, message: '调入部门不能为空', trigger: 'blur' }],
  transferDate: [{ required: true, message: '调动日期不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 部门树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PersonnelTransferApi.getPersonnelTransfer(id)
    } finally {
      formLoading.value = false
    }
  }

  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 保存用户信息
const userInfo = ref({
  id: undefined,
  deptId: undefined
})

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PersonnelTransferVO
    if (formType.value === 'create') {
      await PersonnelTransferApi.createPersonnelTransfer(data)
      message.success(t('common.createSuccess'))
    } else {
      await PersonnelTransferApi.updatePersonnelTransfer(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false

    const userData = userInfo.value as unknown as UserApi.UserVO
    userData.id = data.userId
    userData.deptId = data.newDeptId
    
    await UserApi.updateUserDept(userData)
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    userId: undefined,
    realName: undefined,
    originalDeptId: undefined,
    originalDeptName: undefined,
    newDeptId: undefined,
    newDeptName: undefined,
    transferReason: undefined,
    transferDate: undefined,
  }
  formRef.value?.resetFields()
}


/** 处理选择员工被点击 */
const handleNodeChange = async (row) => {
  formData.value.userId = row.id
  formData.value.realName = row.nickname
  formData.value.originalDeptId = row.deptId
  formData.value.originalDeptName = row.deptName
}


// 调入部门点击事件
const handleNewDeptClick = async(data)=>{
  formData.value.newDeptId = data.id
  formData.value.newDeptName = data.name
}
</script>